package org.csu.bbs.controller;

import org.csu.bbs.entity.Posts;
import org.csu.bbs.entity.UserInfo;
import org.csu.bbs.result.BetterResult;
import org.csu.bbs.result.Result;
import org.csu.bbs.service.PostsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@Controller
public class PostsController {

    @Autowired
    PostsService postsServiceImpl;

    @GetMapping(value = "api/sections/{section_id}/posts")
    @CrossOrigin
    @ResponseBody
    public Object Getposts(@PathVariable(value = "section_id") Integer section_id){
        return postsServiceImpl.GetBySection(section_id);
    }

    @CrossOrigin
    @GetMapping(value = "api/post")
    @ResponseBody
    public Posts viewPosts(@RequestParam( value = "id") int id){
        return postsServiceImpl.getById(id);
    }

    @CrossOrigin
    @GetMapping(value = "api/poster")
    @ResponseBody
    public BetterResult<UserInfo> getPoster(@RequestParam( value = "id") int id){
        return postsServiceImpl.GetPoster(id);
    }

    @CrossOrigin
    @GetMapping("api/posts/search")
    @ResponseBody
    public List<Posts> searchResult(@RequestParam("keywords") String keywords) {
            System.out.println(keywords);
        if ("".equals(keywords)) {
            return postsServiceImpl.GetBySection(0);
        } else {
            return postsServiceImpl.Search(keywords);
        }
    }

    @CrossOrigin
    @PostMapping(value = "api/post")
    @ResponseBody
    public Result addPost(@RequestBody Posts posts){
        return postsServiceImpl.AddPosts(posts);
    }

    @CrossOrigin
    @DeleteMapping("api/post/{id}")
    @ResponseBody
    public int deleteOnePost(@PathVariable(value = "id") Integer id){
       return postsServiceImpl.DeleteOne(id);
    }

    @CrossOrigin
    @GetMapping("api/user/{userid}/posts")
    @ResponseBody
    public List<Posts> GetPersonalPosts(@PathVariable(value = "userid") String userid){
        return postsServiceImpl.GetByUserId(userid);
    }

    @CrossOrigin
    @GetMapping("api/posts/count")
    @ResponseBody
    public ArrayList<Integer> searchCount(){
        return postsServiceImpl.searchCount();
    }
}
